<?php

namespace app\http\controller\chat;

use Laf\Cookie;
use Laf\Session;
use FApi\Response;
use app\libs\View;
use mon\util\Tool;
use Laf\Controller;
use mon\env\Config;
use mon\captcha\Captcha;
use GatewayClient\Gateway;
use app\model\SettingModel;
use app\model\ChatWaiterModel;
use app\model\ChatAccessModel;
use app\model\ChatVisitorModel;
use app\model\ChatNewsAccessModel;
use app\model\ChatMessageRelationModel;

/**
 * 即时通信客服端接口
 */
class WaiterController extends Controller
{
    /**
     * 客服页面
     *
     * @return string
     */
    public function index()
    {
        // 获取用户信息
        $userInfo = Session::instance()->getService()->get(Config::instance()->get('chat.userInfo'));
        // 获取客服关联应用
        $appList = ChatAccessModel::instance()->getBindApp($userInfo['id']);
        $apps = [];
        // 过滤无效的关联应用
        foreach ($appList as $item) {
            if ($item['status'] == '1') {
                $apps[] = $item['name'];
            }
        }


        $template = new View();
        $site = Config::instance()->get('admin.site');
        $config = SettingModel::instance()->getConfig('chat');
        $uid = id2code($userInfo['id']);
        $jsConfig = [
            'server'        => $config['server_address'],
            'app'           => $apps,
            'logo'          => '/static/img/avatar.png',
            'cmd'           => 'reception',
            'uid'           => $uid,
            'title'         => $site['title'],
            'uploadLink'    => $this->url->build('/chat/upload', [], true),
            'login'         => $this->url->build('/chat/waiter/login'),
            'emojiSetting'  => ['path' => '/static/libs/monEmoji/img/']
        ];

        // 种下websocket-ticket
        $socketSafeConfig = Config::instance()->get('socket.safe');
        Cookie::instance()->set($socketSafeConfig['name'], $uid);
        Tool::instance()->createTicket($uid, $socketSafeConfig['salt'], $socketSafeConfig['expire'], $socketSafeConfig['token'], $socketSafeConfig['time']);
        $template->assign('config', $jsConfig);
        $template->assign('site', $site);
        return $template->fetch('/chat/waiter/index');
    }

    /**
     * 获取验证码图片
     *
     * @return void
     */
    public function captcha()
    {
        $id = Config::instance()->get('chat.login_captcha_id');
        $config = Config::instance()->get('captcha');
        $captcha = new Captcha($config);
        $data = $captcha->create($id, false);
        return Response::create($data)->header(['Content-Type' => 'image/png']);
    }

    /**
     * 客服登录
     *
     * @return void
     */
    public function login(ChatWaiterModel $model)
    {
        if ($this->request->isPost()) {
            $option = $this->request->post('', []);
            // 验证图片验证码
            if (!isset($option['captcha']) || empty($option['captcha'])) {
                return $this->error('验证码参数错误');
            }
            $id = Config::instance()->get('chat.login_captcha_id');
            $config = Config::instance()->get('captcha');
            $captcha = new Captcha($config);
            if (!$captcha->check($option['captcha'], $id)) {
                return $this->error('验证码错误');
            }
            $userInfo = $model->login($option);
            if (!$userInfo) {
                return $this->error($model->getError());
            }
            Session::instance()->getService()->set(Config::instance()->get('chat.userInfo'), $userInfo);
            return $this->success('ok', [
                'url' => $this->url->build('/chat/waiter/index')
            ]);
        }
        $template = new View();
        return $template->fetch('/chat/waiter/login', [
            'container' => $this->container,
            'site'      => Config::instance()->get('admin.site')
        ]);
    }

    /**
     * 客服登出
     *
     * @return string
     */
    public function logout()
    {
        Session::instance()->getService()->clear();
        return $this->success('ok', ['url' => $this->url->build('/chat/waiter/login', [], true)]);
    }

    /**
     * 获取客户端游客信息
     *
     * @param string $visitid 游客ID
     * @param ChatVisitorModel $model 游客模型
     * @return void
     */
    public function getClientInfo($visitid, ChatVisitorModel $model)
    {
        if (empty($visitid)) {
            return $this->error('params invalid');
        }

        $info = $model->where('visitid', $visitid)->find();
        return $this->success('ok', $info);
    }

    /**
     * 更新保存客户端游客信息
     *
     * @param string $visitid 游客ID
     * @param ChatVisitorModel $model 游客模型
     * @return void
     */
    public function saveClientInfo($visitid, ChatVisitorModel $model)
    {
        if (empty($visitid)) {
            return $this->error('params invalid');
        }
        // 获取参数，验证参数
        $data = $this->request->post();
        $save = $model->modify($data, $visitid);
        if (!$save) {
            return $this->error($model->getError());
        }

        return $this->success('ok');
    }

    /**
     * 加载历史会话
     *
     * @return void
     */
    public function history(ChatMessageRelationModel $model)
    {
        $data = $this->request->post();
        $data['waiter_id'] = Session::instance()->getService()->get(Config::instance()->get('chat.userInfo') . '.id');
        $list = $model->getList($data);
        return $this->success('ok', $list);
    }

    /**
     * 修改密码
     *
     * @return void
     */
    public function modifyPassword(ChatWaiterModel $model)
    {
        $data = $this->request->post();
        $data['idx'] = Session::instance()->getService()->get(Config::instance()->get('chat.userInfo') . '.id');
        $save = $model->reset_password($data, true);
        if (!$save) {
            return $this->error($model->getError());
        }

        return $this->success('修改密码成功');
    }

    /**
     * 获取允许转接的app客服人员列表
     *
     * @return void
     */
    public function transfer()
    {
        $app = $this->request->post('app');
        if (!$app) {
            return $this->error('query faild');
        }

        $uid = Session::instance()->get(Config::instance()->get('chat.userInfo') . '.id');
        if (!$uid) {
            return $this->error('获取可转接客服异常');
        }
        try {
            $data = [];
            $uids = [];
            $id_code = [];
            Gateway::$registerAddress = Config::instance()->get('socket.gateway.registerAddress');
            // 获取在线客服
            $onLineKWaiter = Gateway::getClientSessionsByGroup("kf_" . $app);
            foreach ($onLineKWaiter as $waiterSession) {
                $id = code2id($waiterSession['uid']);
                if ($id == $uid) {
                    // 跳过自身
                    continue;
                }
                $uids[] = $id;
                $id_code[$id] = $waiterSession['uid'];
            }

            // 获取所有可转接客服的信息
            $waiterList =  ChatWaiterModel::instance()->where('id', 'in', $uids)->where('status', 1)->field(['id', 'account', 'nickname'])->select();
            // 整理返回数据
            foreach ($waiterList as $item) {
                $data[] = [
                    'uid' => $id_code[$item['id']],
                    'nickname' => $item['nickname'],
                    'account' => $item['account']
                ];
            }
        } catch (\Exception $e) {
            $data = [];
        }

        return $this->success('ok', $data);
    }

    /**
     * 获取图文信息
     *
     * @return void
     */
    public function news()
    {
        $app = $this->request->post('app');
        if (!$app) {
            return $this->error('query faild');
        }
        $list = ChatNewsAccessModel::instance()->getBindApp($app);
        return $this->success('ok', $list);
    }
}
